
StackPlot  <- function(object, xgroup, ygroup, isStack=T, hline=NULL, cols = NULL) {
  data <- FetchData(object, vars = c(xgroup, ygroup))
  colnames(data) <- c("xgroup", "ygroup")
  # 计算每个组中每个子组的出现次数
  data_percent <- data %>%
    group_by(xgroup, ygroup) %>%
    summarise(count = n(), .groups = "drop") %>%
    # ungroup()  %>%
    group_by(xgroup) %>%
    mutate(percentage = count / sum(count)) %>%
    ungroup()
  
  if (isStack) {
    # 绘制百分比堆叠柱状图
    p <- ggplot(data_percent, aes(x = xgroup, y = percentage, fill = ygroup)) +
      geom_bar(stat = "identity", position = "fill") + 
      scale_y_continuous(labels = scales::percent) + 
      labs(title = "", x = "", y = "") +
      theme_minimal() + theme(legend.title = element_blank())
    if (!is.null(hline) && is.numeric(hline)) {
      p <- p + geom_hline(yintercept = hline, linetype = "dashed", color = "red") +
        annotate("text", x = 1.5, y = 0.82, label = scales::percent(hline), color = "red") 
    }
  } else {
    # 绘制堆叠柱状图
    p <- ggplot(data_percent, aes(x = xgroup, y = count, fill = ygroup)) +
      geom_bar(stat = "identity") +
      labs(title = "", x = "", y = "") +
      theme_minimal() + theme(legend.title = element_blank())
  }
  if (!is.null(cols)) {
    p <- p + scale_fill_manual(values = cols) 
  }
  p
}

